package huixue.cn.com.library.interceptor;

import android.support.annotation.NonNull;
import android.util.Log;

import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import huixue.cn.com.library.util.HttpLog;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by gongdongyang on 2018/7/17.
 */

public class LoggerIntercepter implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Log.d("ChannelIndex","==intercept==");
        final Request request = chain.request();
        Buffer requestBuffer = new Buffer();
        if (request.body() != null) {
            request.body().writeTo(requestBuffer);
        } else {
            Logger.d("LogTAG", "request.body() == null");
        }
        //打印url信息
        HttpLog.w(request.url() + (request.body() != null ? "?" + _parseParams(request.body(), requestBuffer) : ""));
        final Response response = chain.proceed(request);
        HttpLog.w(response.body().string());

        return response;
    }

    @NonNull
    private static String _parseParams(RequestBody body, Buffer requestBuffer) throws UnsupportedEncodingException {
        if (body.contentType() != null && !body.contentType().toString().contains("multipart")) {
            return URLDecoder.decode(requestBuffer.readUtf8(), "UTF-8");
        }
        return "null";
    }
}
